<template>
  <view class="evaluate-container">
    <!-- 1. 顶部导航栏 -->
    <view class="top-nav">
      <view class="nav-left" @click="navigateBack">
        <uni-icons class="back-icon" type="left" size="20" color="#fff"></uni-icons>
      </view>
      <text class="nav-title">评价管理</text>
      <view class="nav-right"></view> <!-- 占位，保持标题居中 -->
    </view>

    <!-- 2. 筛选与搜索区 -->
    <view class="filter-search-bar">
      <!-- 星级筛选 -->
      <view class="star-filter">
        <text class="filter-label">星级筛选：</text>
        <view class="star-options">
          <view 
            class="star-option" 
            :class="{ active: selectedStar === 'all' }" 
            @click="selectStar('all')"
          >全部</view>
          <view 
            class="star-option" 
            :class="{ active: selectedStar === '5' }" 
            @click="selectStar('5')"
          >
            <text class="star">★</text> 5星
          </view>
          <view 
            class="star-option" 
            :class="{ active: selectedStar === '4' }" 
            @click="selectStar('4')"
          >
            <text class="star">★</text> 4星
          </view>
          <view 
            class="star-option" 
            :class="{ active: selectedStar === '3' }" 
            @click="selectStar('3')"
          >
            <text class="star">★</text> 3星
          </view>
          <view 
            class="star-option" 
            :class="{ active: selectedStar === '2' }" 
            @click="selectStar('2')"
          >
            <text class="star">★</text> 2星
          </view>
          <view 
            class="star-option" 
            :class="{ active: selectedStar === '1' }" 
            @click="selectStar('1')"
          >
            <text class="star">★</text> 1星
          </view>
        </view>
      </view>

      <!-- 搜索框 -->
      <view class="search-box">
        <text class="search-icon">🔍</text>
        <input 
          class="search-input" 
          placeholder="搜索评价内容..." 
          v-model="searchKeyword"
          @input="filterEvaluate"
        />
      </view>
    </view>

    <!-- 3. 评价列表区 -->
    <view class="evaluate-list">
      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading && realEvaluateData.length === 0">
        <uni-icons type="loading" size="30" color="#5555ff" spin></uni-icons>
        <text class="loading-text">加载评价中...</text>
      </view>

      <!-- 评价列表 -->
      <view 
        class="evaluate-item" 
        v-for="(item, index) in filteredEvaluates" 
        :key="index"
        v-show="!loading"
      >
        <!-- 评价头部：用户信息+星级+时间 -->
        <view class="evaluate-header">
          <view class="user-info">
            <view class="user-avatar">{{ item.userName.charAt(0) }}</view>
            <text class="user-name">{{ item.userName }}</text>
          </view>
          <view class="evaluate-meta">
            <view class="star-rating">
              <text class="star" v-for="i in 5" :key="i" :class="{ active: i <= item.star }">★</text>
            </view>
            <text class="evaluate-time">{{ item.time }}</text>
          </view>
        </view>

        <!-- 评价内容+关联工单 -->
        <view class="evaluate-content">
          <text class="content-text">{{ item.content }}</text>
          <view 
            class="order-link" 
            @click="toOrderDetail(item.orderId)"
            :class="{ disabled: !item.orderId }"
          >
            关联工单：{{ item.orderId || '无' }}
          </view>
        </view>
      </view>

      <!-- 空状态提示 -->
      <view class="empty-state" v-if="!loading && filteredEvaluates.length === 0">
        <text class="empty-icon">⭐</text>
        <text class="empty-text">
          {{ hasFilter ? '未找到匹配的评价' : '暂无您处理工单的评价' }}
        </text>
      </view>
    </view>
  </view>
</template>

<script>
import request from '@/api/request.js';
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';

export default {
  components: {
    uniIcons
  },
  data() {
    return {
      token: uni.getStorageSync('token') || '', // 登录Token
      // 分页参数
      pageNo: 1,
      pageSize: 10,
      total: 0,
      // 接口状态
      loading: false,
      realEvaluateData: [], // 真实评价数据
      // 筛选条件
      selectedStar: 'all',
      searchKeyword: ''
    };
  },
  computed: {
    // 过滤后的评价列表
    filteredEvaluates() {
      let result = [...this.realEvaluateData];

      // 星级筛选
      if (this.selectedStar !== 'all') {
        const targetStar = parseInt(this.selectedStar);
        result = result.filter(item => item.star === targetStar);
      }

      // 关键词搜索
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.trim().toLowerCase();
        result = result.filter(item => 
          item.content.toLowerCase().includes(keyword)
        );
      }

      return result;
    },
    // 判断是否有筛选条件
    hasFilter() {
      return this.selectedStar !== 'all' || this.searchKeyword.trim() !== '';
    }
  },
  onLoad() {
    // 页面加载时获取评价数据
    this.getEmployeeEvaluateList();
  },
  onReachBottom() {
    // 下拉加载更多
    if (this.loading) return;
    
    // 检查是否还有更多数据
    if (this.realEvaluateData.length >= this.total) {
      uni.showToast({ title: '已加载全部评价', icon: 'none', duration: 1000 });
      return;
    }
    
    // 加载下一页
    this.pageNo += 1;
    this.getEmployeeEvaluateList();
  },
  methods: {
    // 返回上一页
    navigateBack() {
      uni.navigateBack({ delta: 1 });
    },
    
    // 选择星级筛选
    selectStar(star) {
      this.selectedStar = star;
    },
    
    // 搜索评价
    filterEvaluate() {
      // 可添加防抖处理
    },
    
    // 时间格式化（兼容带时区的ISO格式）
    formatDate(date) {
      if (!date) return '';
      // 处理带时区的ISO字符串（如 "2025-09-23T01:59:30.000+0000"）
      if (typeof date === 'string' && date.includes('T') && date.includes('+')) {
        date = date.split('+')[0].replace('T', ' ');
      }
      // 处理普通字符串/时间戳
      const dateObj = new Date(date);
      const year = dateObj.getFullYear();
      const month = String(dateObj.getMonth() + 1).padStart(2, '0');
      const day = String(dateObj.getDate()).padStart(2, '0');
      const hour = String(dateObj.getHours()).padStart(2, '0');
      const minute = String(dateObj.getMinutes()).padStart(2, '0');
      const second = String(dateObj.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    
    // 获取评价列表
    async getEmployeeEvaluateList() {
      // 登录校验
      if (!this.token) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        setTimeout(() => {
          uni.redirectTo({ url: '/pages/login/login' });
        }, 1500);
        return;
      }

      this.loading = true;
      try {
        // 构造请求参数
        const requestBody = {
          pageNo: this.pageNo,
          pageSize: this.pageSize
        };

        // 调用后端接口
        const response = await request.postJson(
          '/api/customerFeedback/queryPageList',
          requestBody,
          true,
          { Token: this.token }
        );

        // 从响应中获取分页数据
        const pageData = response.data?.data || response;
        this.total = pageData.total || 0;
        
        // 映射数据格式：从 workOrderInfo 中提取 employeeName
        const evaluates = (pageData.records || []).map(dto => {
          // 关键修改：从嵌套的 workOrderInfo 对象中获取 employeeName
          let userName = (dto.workOrderInfo && dto.workOrderInfo.employeeName) || '匿名客户';
          
          // 处理名称为空/纯空格/“匿名”的情况
          if (!userName.trim() || userName.trim() === '匿名') {
            userName = '匿名客户';
          }
          
          return {
            userName: userName,
            star: dto.rating || 0,
            time: this.formatDate(dto.createTime),
            content: dto.comment || '无评价内容',
            orderId: dto.orderId || dto.id || ''
          };
        });

        // 分页数据处理
        if (this.pageNo === 1) {
          this.realEvaluateData = evaluates;
        } else {
          this.realEvaluateData = this.realEvaluateData.concat(evaluates);
        }

      } catch (error) {
        // 错误处理
        let errMsg = '获取评价列表失败，请重试';
        if (error.code === 100002) {
          errMsg = '无法获取员工信息，请重新登录';
        } else if (error.code === 100003) {
          errMsg = '登录已过期，请重新登录';
          uni.removeStorageSync('token');
          setTimeout(() => {
            uni.redirectTo({ url: '/pages/login/login' });
          }, 1500);
        } else if (error.code === 100001) {
          errMsg = '系统异常，请稍后重试';
        }
        uni.showToast({ title: errMsg, icon: 'none' });
      } finally {
        this.loading = false;
      }
    },
    
    // 跳转至工单详情
    toOrderDetail(orderId) {
      console.log('尝试跳转到工单详情，工单ID:', orderId);
      
      if (!orderId || orderId === 'undefined' || orderId === 'null') {
        uni.showToast({ title: '工单ID异常，无法查看详情', icon: 'none' });
        return;
      }
      
      uni.navigateTo({ 
        url: `/pages/Employee/workorder/detail?id=${orderId}` 
      });
    }
  }
};
</script>

<style scoped>
/* 页面容器 */
.evaluate-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

/* 顶部导航栏 */
.top-nav {
  height: 100rpx;
  background-color: #5555ff;
  display: flex;
  align-items: center;
  padding: 0 32rpx;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 99;
}
.nav-left {
  width: 44rpx;
  height: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.back-icon {
  font-size: 32rpx;
  color: #fff;
}
.nav-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  color: #fff;
  font-weight: bold;
}
.nav-right {
  width: 44rpx;
  height: 44rpx;
}

/* 筛选与搜索区 */
.filter-search-bar {
  padding: 120rpx 24rpx 16rpx; /* 避开顶部导航 */
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}
/* 星级筛选 */
.star-filter {
  margin-bottom: 16rpx;
}
.filter-label {
  font-size: 26rpx;
  color: #666;
  margin-right: 16rpx;
}
.star-options {
  display: flex;
  overflow-x: auto;
  white-space: nowrap;
  padding-bottom: 8rpx;
}
.star-option {
  padding: 8rpx 16rpx;
  margin-right: 12rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: #666;
  background-color: #f0f0f0;
  cursor: pointer;
  display: flex;
  align-items: center;
}
.star-option .star {
  color: #ffd700;
  margin-right: 4rpx;
}
.star-option.active {
  background-color: #5555ff;
  color: #fff;
}
.star-option.active .star {
  color: #fff;
}
/* 搜索框 */
.search-box {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 0 20rpx;
  height: 68rpx;
}
.search-icon {
  font-size: 28rpx;
  color: #999;
  margin-right: 12rpx;
}
.search-input {
  flex: 1;
  height: 100%;
  font-size: 26rpx;
  color: #333;
  background-color: transparent;
}

/* 评价列表区 */
.evaluate-list {
  flex: 1;
  padding: 16rpx 24rpx;
  overflow-y: auto;
}

/* 加载状态样式 */
.loading-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300rpx;
  color: #5555ff;
  font-size: 28rpx;
}
.loading-text {
  margin-top: 16rpx;
}

/* 评价项 */
.evaluate-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}
/* 评价头部：用户信息+星级+时间 */
.evaluate-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}
.user-info {
  display: flex;
  align-items: center;
}
.user-avatar {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  background-color: #5555ff;
  color: #fff;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16rpx;
}
.user-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}
.evaluate-meta {
  display: flex;
  align-items: center;
  gap: 16rpx;
}
.star-rating .star {
  font-size: 24rpx;
  color: #ddd;
}
.star-rating .star.active {
  color: #ffd700;
}
.evaluate-time {
  font-size: 22rpx;
  color: #999;
}
/* 评价内容+关联工单 */
.evaluate-content {
  border-top: 1rpx dashed #eee;
  padding-top: 16rpx;
}
.content-text {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
  display: block;
  margin-bottom: 12rpx;
}
.order-link {
  font-size: 24rpx;
  color: #5555ff;
  cursor: pointer;
}
.order-link.disabled {
  color: #999;
  cursor: not-allowed;
  text-decoration: none;
}
.order-link:active {
  text-decoration: underline;
}

/* 空状态提示 */
.empty-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  color: #999;
  font-size: 30rpx;
  margin-top: 50rpx;
}
.empty-icon {
  font-size: 80rpx;
  margin-bottom: 24rpx;
  color: #ddd;
}
</style>
